<template>
    <section>

        <!--高级查询搜索框-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="searchForm">
                <el-form-item>
                    <el-input v-model="searchForm.name" placeholder="部门"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--
                 :data="departments":绑定的数据
        -->
        <el-table :data="departments"  v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <!--显示复选框-->
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!--显示序号-->
            <el-table-column type="index" width="100" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="部门" >
            </el-table-column>
            <el-table-column prop="sn" label="编号" >
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatState"  >
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" >
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" >
            </el-table-column>

            <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination  :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"  @size-change="handleSizeChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--
           新增/编辑界面
           title：弹出框标题
           addFormVisible:是否显示弹出框
           :model="addForm":双向绑定的公共前缀
           :rules="addFormRules":申明校验规则
           ref="addForm":简单理解就是form申明唯一的id
       -->
        <el-dialog :title="title" v-model="addFormVisible" >
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="部门" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="addForm.sn"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="1">启用</el-radio>
                        <el-radio class="radio" :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="addForm.deptId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in depts"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门经理">
                    <el-select v-model="addForm.managerId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>

    export default {
        name: "",
        data(){
            return {
                //弹出框标题
                title:"",
                //是否显示弹出框
                addFormVisible:false,
                //添加/修改弹出框中的form
                addForm:{
                    id:"",
                    name:"",
                    sn:"",
                    state:1,
                    deptId:null,
                    managerId:""
                },

                //高级查询表单
                searchForm:{
                    name: "",
                    state: ""
                },
                //当前页
                currentPage:1,
                //每页显示数目的条数
                pageSize:5,
                //数据总条数
                total: 0,
                //选中复选框对应的值
                sels:[],
                //部门列表数据
                departments: [],
                //显示加载框
                listLoading: false,
                //部门列表
                depts:[],
                //部门经理
                managers:[],
                addFormRules: {
                    name: [
                        {required: true, message: '部门必填！!', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '编号必填！!', trigger: 'blur'}
                    ]
                }
            }
        },

        methods:{

            //选中复选框触发此函数
            selsChange(Vals){
                this.sels=Vals;
            },

            //修改每页显示条数
            handleSizeChange(val){
                this.pageSize=val;
                this.loadDepartments();
            },
            //批量删除按钮
            batchRemove(){
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true ;
                    //NProgress.start();  this.sels是一个json数组
                    this.$http.patch("/department/batchRemove",this.sels).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.loadDepartments();
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true ;
                    //NProgress.start();
                    this.$http.delete("/department/"+row.id).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.loadDepartments();
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //页码参数发生改变的时候触发此函数
            handleCurrentChange(val){
                //从新设置当前页
                this.currentPage=val;
                //从新刷新页面
                this.loadDepartments();
            },

            //性别显示转换    row当前行对应的值，column列属性的介绍
            formatState: function (row) {
                return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
            },

            //加载部门列表
            loadDepartments(){
                this.listLoading=true;//显示加载框

                //传递分页参数
                let param = {
                    "currentPage": this.currentPage,
                    "pageSize": this.pageSize,
                    "name": this.searchForm.name,
                    "state": this.searchForm.state
                };

                this.$http.patch("/department",param).then((res => {
                    let {result,total}=res.data;
                    this.departments=result;
                    this.total=total;
                    this.listLoading = false;
                    }));
            },

            //加载所有的部门列表
            loadAllDepartments(){
                this.$http.patch("/department/loadAll").then((res => {
                    this.depts = res.data;
                }));
            },

            //加载所有的员工列表
            loadAllEmployees(){
                this.$http.patch("/employee/loadAll").then((res => {
                    this.managers = res.data;
                }));
            },

            //新增弹出窗体
            handleAdd(){
                //设置标题
                this.title = "新增";
                if(this.$refs["addForm"]){
                    //重置
                    this.$refs["addForm"].resetFields();//this.$refs.addForm.resetFields()
                }
                //清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                }
                //默认是启用状态
                this.addForm.state = 1;
                //显示弹出框
                this.addFormVisible = true;
            },

            //点击确认添加
            addSubmit(){
                if(this.addForm.deptId){
                    //给addForm动态添加属性
                    this.addForm.parent = {"id":this.addForm.deptId}
                }else {
                    this.addForm.parent = {"id":""}
                }


                if(this.addForm.managerId){
                    //给addForm动态添加属性
                    this.addForm.manager = {"id": this.addForm.managerId};
                }else {
                    this.addForm.manager = {"id":""}
                }


                //必须验证通过之后，才执行if语句中的内容
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$http.post("/department", this.addForm).then((res => {
                            let {success, msg} = res.data;
                            if(success){
                                //关闭弹出框
                                this.addFormVisible = false;
                                //刷新列表
                                this.loadDepartments();
                            }else{
                                //刷新列表
                                this.loadDepartments();
                                this.$message.error(msg);
                            }
                        }));
                    }
                });
            },

            //编辑弹出框
            handleEdit(index,row){
                //循环form表单（解决普通赋值）
                for(var k in this.addForm){
                    this.addForm[k] = row[k];
                }
                //给部门了经理赋值
                if(row.manager){
                    this.addForm.managerId = row.manager.id;
                }
                //给部门赋值
                if(row.parent){
                    this.addForm.deptId = row.parent.id;
                }
                //弹出窗体
                this.addFormVisible = true;
            },
        },

        mounted() {
            //加载部门列表 有分页
            this.loadDepartments();
            //加载部门列表
            this.loadAllDepartments();
            //加载部门经理列表
            this.loadAllEmployees();
        }
    };
</script>

<style scoped>

</style>